package com.hl.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xuemiao
 * @create 2023/9/26 18:39
 * @description
 */
@WebFilter("/*")
public class  CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //设置字符集
        servletRequest.setCharacterEncoding("utf-8");
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //设置返回前端数据的格式
        response.setContentType("application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*"); // 设置允许的域名，使用通配符 * 表示允许所有域名
        response.setHeader("Access-Control-Allow-Methods", "*"); // 允许的HTTP方法
        response.setHeader("Access-Control-Allow-Headers", "*"); // 允许的请求头
        response.setHeader("Access-Control-Allow-Credentials", "true");//允许cookie
        response.setHeader("Access-Control-Max-Age", "3600"); // 预检请求的有效期，单位为秒
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
